package com.karl.leetcode.test.medium.solution;

import com.karl.leetcode.test.medium.model.SolutionInfo;
import com.karl.leetcode.test.medium.topic.AddTwoNumbers;

/**
 * 两数加和:默认解题
 *
 * @author 李克国
 * @version 1.0.0
 * @project leetcode-test
 * @date 2020/12/31 10:30
 * @description 两数加和:默认解题
 * @see AddTwoNumbers
 */
public class AddTwoNumbersFastSolution extends AddTwoNumbers implements Solution {
    ListNode l1 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))))));
    ListNode l2 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))));

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int value =  l1.val +  l2.val;
        if (l1.next == null && l2.next == null) {
            if (value >= 10) {
                return new ListNode(value % 10, new ListNode(1));
            }
            return new ListNode(value);
        }
        if (l1.next == null) {
            l1.next = new ListNode(0);
        }
        if (l2.next == null) {
            l2.next = new ListNode(0);
        }
        ListNode noxt = addTwoNumbers(l1.next, l2.next);
        if (value >= 10) {
            noxt.val = noxt.val + 1;
            update(noxt);
            value = value % 10;
        }
        return new ListNode(value, noxt);
    }

    private void update(ListNode node) {
        if (node == null || node.val < 10) {
            return;
        }
        node.val = node.val % 10;
        node.next = node.next == null ? new ListNode(0) : node.next;
        node.next.val = node.next.val + 1;
        update(node.next);
    }

    @Override
    public SolutionInfo getSolutionInfo() {
        return SolutionInfo.builder().name("默认解决方案").build();
    }

    @Override
    public void run() {
        System.out.println("用例：");
        show(l1, "l1");
        show(l2, "l2");
        ListNode res = addTwoNumbers(l1, l2);
        show(res, "结果");
    }

    public void setL1(ListNode node) {
        l1 = node;
    }

    public void setL2(ListNode node) {
        l2 = node;
    }

    private void show(ListNode res, String name) {
        System.out.print(name + ": \t");
        show(res);
    }

    private void show(ListNode res) {
        while (res != null) {
            System.out.print(res.val + "\t");
            res = res.next;
        }
        System.out.println();
    }
}
